package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 30000)
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
/*
* 1. 在默认频道展示10条文章信息
2. 可以切换频道查看不同种类文章
3. 当用户上拉可以加载更多的文章信息（按照发布时间）
   - 分页
   - 本页文章列表中发布时间为最小的时间为依据
4. 当用户下拉可以加载最新的文章
   - 本页文章列表中发布时间最大的时间为依据
* */

    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    private String readPath;
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1.校验数据
        Integer size = dto.getSize();
        if(size==null|| size<=0){
            size=10;
        }
        dto.setSize(size);
        //2.频道
        String tag = dto.getTag();
        if(StringUtils.isBlank(tag)){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //3.时间
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //类型
        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)||!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)){
            loadtype=ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            // 获取文章封面字段
            String images = article.getImages();
            if (StringUtils.isNotBlank(images)) {
                // 将封面按照,号切割   生成流
                images = Arrays.stream(images.split(","))
                        // 每一个路径添加前缀
                        .map(url -> webSite + url)
                        // 将加了前缀的路径  拼接成字符串
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }

            //拼接文章url
            article.setStaticUrl( readPath + article.getStaticUrl());
        }
        ResponseResult result= ResponseResult.okResult(articleList);

        return result;
    }

    @Autowired
    GeneratePageService generatePageService;
    @Override
    public void publishArticle(Integer newsId) {
        //1. 根据 文章id 查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        // 2. 根据wmNews信息封装ApArticle对象
        ApArticle article = parseApArticle(wmNews);
        System.out.println(article);
        //3.保存或修改apArticle对象
        saveOrUpdateArticle(article);
        //4.保存配置信息和内容信息
        saveConfigAndContent(article,wmNews);
        //5.TODO 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        //6.修改Wmnews状态 状态改为9 并设置管理的articleID
        updateWmNews(wmNews,article);



        //7.TODO MQ通知es索引库更新文章索引
    }

    private void updateWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }

    }

    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        //保存文章配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true);//是否允许评论
        config.setIsForward(true);//转发
        config.setIsDown(false);//下架
        config.setIsDelete(false);//删除
        apArticleConfigService.save(config);
        //2. 保存文章内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);
    }

    @Autowired
    ApArticleConfigService apArticleConfigService;

    @Autowired
    ApArticleContentService apArticleContentService;

    private void saveOrUpdateArticle(ApArticle article) {
        if (article.getId() == null) {
            //保存
            article.setViews(0);
            article.setLikes(0);
            article.setComment(0);
            article.setCollection(0);
            this.save(article);
        } else {
            //改之前要删除关联的 文章配置信息 和文章详情信息  因为后面要重新配置
            apArticleConfigService.remove(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, article.getId()));
            apArticleContentService.remove(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
            //修改
            this.updateById(article);

        }
    }

    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorService authorService;

    private ApArticle parseApArticle(WmNews wmNews) {
        //1. 创建article 将wmNews的同名属性拷贝进去
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews, article);
        //2. 单独设置articleID字段
        article.setId(wmNews.getArticleId());
        //3.需要补充其他字段 flag layout
        article.setLayout(wmNews.getType());
        article.setFlag((byte) 0);
        //4.频道id
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        AdChannel channel = channelResult.getData();
        article.setChannelName(channel.getName());
        //5.作者信息
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        return article;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    private WmNews getWmNews(Integer newsId) {
        //1. 根据ID使用feign接口远程查询
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //判断是否为空
        WmNews wmNews = result.getData();
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //必须是4或8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status) && !WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章 不是审核通过的状态，发布失败");
        }
        return wmNews;


    }
}